package com.example.qiniutest.image.service.impl;

import com.example.qiniutest.image.config.QiniuConfig;
import com.example.qiniutest.image.service.FileService;
import com.example.qiniutest.image.tonken.service.TokenService;
import com.example.qiniutest.image.vo.FileVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Md5;
import com.qiniu.util.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

@Service
public class IFileService implements FileService {

    @Autowired
    TokenService tokenService;

    @Autowired
    QiniuConfig qiniuConfig;

    @Override
    public FileVo upload(MultipartFile fileInput,boolean isTimestamp) {
        if (fileInput==null || !StringUtils.hasLength(fileInput.getOriginalFilename())) {
            return new FileVo(false,"555","文件名不得为空");
        }

        if (!validateFileName(fileInput.getOriginalFilename())){
            return new FileVo(false,"565","文件名应仅包含汉字、字母、数字、下划线和点号");
        }

        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager=new UploadManager(cfg);
        String token = tokenService.getToken();
        DefaultPutRet putRet=null;
        try {
            Response rsp = uploadManager.put(fileInput.getInputStream(), null, token, null, null);
            putRet = new ObjectMapper().readValue(rsp.bodyString(),DefaultPutRet.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Auth auth = tokenService.getAuth();
/*        if (isTimestamp){
            return new FileVo(timeStampToPreventTheft(putRet.key));
        }*/
        String timeStamp = timeStampToPreventTheft(putRet.key);
//        String uri=qiniuConfig.url+putRet.key;
        String uri=timeStamp;
        uri = auth.privateDownloadUrl(uri, QiniuConfig.TEN_YEAR);
        return new FileVo(uri);

    }


    @Override
    public String timeStampToPreventTheft(String path) {
        long expires = System.currentTimeMillis() / 1000L + QiniuConfig.TEN_YEAR;
        String hexadecimal = timeHexadecimal(expires);
        String s=qiniuConfig.key+pathEncode("/"+path)+ hexadecimal;
        String sign = Md5.md5(s.getBytes()).toLowerCase();
        return qiniuConfig.url+path+"?sign="+sign+"&t="+hexadecimal;
    }

    public String pathEncode(String path){
        return UrlUtils.urlEncode(path);
    }

    public String timeHexadecimal(long time){
        return Long.toHexString(time).toLowerCase();
    }

    private boolean validateFileName(String fileName) {
        String regex = "^[a-zA-Z0-9_\\u4e00-\\u9fa5_\\.]+$";
        return fileName.matches(regex);
    }
}
